package com.example.huixue.service;

import com.example.huixue.common.PageResult;
import com.example.huixue.dto.LoginRequest;
import com.example.huixue.dto.RegisterRequest;
import com.example.huixue.dto.UserInfoResponse;
import com.example.huixue.entity.User;
import com.example.huixue.mapper.UserMapper;
import com.example.huixue.util.JwtUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserService {
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    
    /**
     * 根据用户名或邮箱查找用户
     */
    public User findByUsernameOrEmail(String usernameOrEmail) {
        User user = userMapper.findByUsername(usernameOrEmail);
        if (user == null) {
            user = userMapper.findByEmail(usernameOrEmail);
        }
        return user;
    }
    
    /**
     * 更新用户最后登录时间
     */
    public void updateLastLogin(Integer userId, LocalDateTime lastLogin) {
        userMapper.updateLastLogin(userId, lastLogin);
    }
    
    /**
     * 检查用户名是否已存在
     */
    public boolean existsByUsername(String username) {
        return userMapper.findByUsername(username) != null;
    }
    
    /**
     * 检查邮箱是否已存在
     */
    public boolean existsByEmail(String email) {
        return userMapper.findByEmail(email) != null;
    }
    
    /**
     * 保存用户
     */
    public User save(User user) {
        userMapper.insert(user);
        return user;
    }
    
    /**
     * 根据ID查找用户
     */
    public User findById(Integer userId) {
        return userMapper.findById(userId);
    }
    
    /**
     * 根据用户名查找用户
     */
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }
    
    /**
     * 根据邮箱查找用户
     */
    public User findByEmail(String email) {
        return userMapper.findByEmail(email);
    }
    
    /**
     * 更新用户信息（通用方法）
     */
    public void update(User user) {
        int result = userMapper.update(user);
        if (result <= 0) {
            throw new RuntimeException("更新用户信息失败");
        }
    }
    
    /**
     * 用户注册
     */
    public UserInfoResponse register(RegisterRequest request) {
        // 验证密码是否一致
        if (!request.getPassword().equals(request.getConfirmPassword())) {
            throw new RuntimeException("两次输入的密码不一致");
        }
        
        // 检查用户名是否已存在
        if (userMapper.findByUsername(request.getUsername()) != null) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 检查邮箱是否已存在
        if (userMapper.findByEmail(request.getEmail()) != null) {
            throw new RuntimeException("邮箱已被注册");
        }
        
        // 创建新用户
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(passwordEncoder.encode(request.getPassword()));
        user.setEmail(request.getEmail());
        user.setPhone(request.getPhone());
        user.setRegisterDate(LocalDateTime.now());
        user.setUserRole("USER");
        user.setStatus("ACTIVE");
        
        // 保存用户
        int result = userMapper.insert(user);
        if (result <= 0) {
            throw new RuntimeException("用户注册失败");
        }
        
        // 生成JWT token
        String token = jwtUtil.generateToken(user.getUserId(), user.getUsername(), user.getUserRole());
        
        // 返回用户信息
        return convertToUserInfoResponse(user, token);
    }
    
    /**
     * 用户登录
     */
    public UserInfoResponse login(LoginRequest request) {
        // 查找用户
        User user = userMapper.findByUsername(request.getUsername());
        if (user == null) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        // 验证密码
        if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        // 更新最后登录时间
        userMapper.updateLastLogin(user.getUserId(), LocalDateTime.now());
        user.setLastLogin(LocalDateTime.now());
        
        // 生成JWT token
        String token = jwtUtil.generateToken(user.getUserId(), user.getUsername(), user.getUserRole());
        
        // 返回用户信息
        return convertToUserInfoResponse(user, token);
    }
    
    /**
     * 获取用户信息
     */
    public UserInfoResponse getUserInfo(Integer userId) {
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        return convertToUserInfoResponse(user, null);
    }
    
    /**
     * 更新用户信息
     */
    public UserInfoResponse updateUserInfo(Integer userId, User updateUser) {
        User existingUser = userMapper.findById(userId);
        if (existingUser == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 检查用户名是否已被其他用户使用
        if (StringUtils.hasText(updateUser.getUsername()) && 
            !updateUser.getUsername().equals(existingUser.getUsername())) {
            User userWithSameName = userMapper.findByUsername(updateUser.getUsername());
            if (userWithSameName != null && !userWithSameName.getUserId().equals(userId)) {
                throw new RuntimeException("用户名已存在");
            }
            existingUser.setUsername(updateUser.getUsername());
        }
        
        // 检查邮箱是否已被其他用户使用
        if (StringUtils.hasText(updateUser.getEmail()) && 
            !updateUser.getEmail().equals(existingUser.getEmail())) {
            User userWithSameEmail = userMapper.findByEmail(updateUser.getEmail());
            if (userWithSameEmail != null && !userWithSameEmail.getUserId().equals(userId)) {
                throw new RuntimeException("邮箱已被使用");
            }
            existingUser.setEmail(updateUser.getEmail());
        }
        
        // 更新其他字段
        if (StringUtils.hasText(updateUser.getPhone())) {
            existingUser.setPhone(updateUser.getPhone());
        }
        if (StringUtils.hasText(updateUser.getProfilePicture())) {
            existingUser.setProfilePicture(updateUser.getProfilePicture());
        }
        
        // 保存更新
        int result = userMapper.update(existingUser);
        if (result <= 0) {
            throw new RuntimeException("更新用户信息失败");
        }
        
        return convertToUserInfoResponse(existingUser, null);
    }
    
    /**
     * 修改密码
     */
    public void changePassword(Integer userId, String oldPassword, String newPassword) {
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 验证旧密码
        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            throw new RuntimeException("原密码错误");
        }
        
        // 更新密码
        String encodedNewPassword = passwordEncoder.encode(newPassword);
        int result = userMapper.updatePassword(userId, encodedNewPassword);
        if (result <= 0) {
            throw new RuntimeException("修改密码失败");
        }
    }
    
    /**
     * 分页查询用户列表（管理员功能）
     */
    public PageResult<UserInfoResponse> getUsersWithPagination(int current, int size, String keyword) {
        int offset = (current - 1) * size;
        
        List<User> users;
        long total;
        
        if (StringUtils.hasText(keyword)) {
            users = userMapper.searchUsers(keyword, offset, size);
            total = userMapper.countSearchUsers(keyword);
        } else {
            users = userMapper.findUsersWithPagination(offset, size);
            total = userMapper.countUsers();
        }
        
        List<UserInfoResponse> userInfoList = users.stream()
                .map(user -> convertToUserInfoResponse(user, null))
                .collect(Collectors.toList());
        
        return new PageResult<>(userInfoList, total, current, size);
    }
    
    /**
     * 更新用户角色（管理员功能）
     */
    public void updateUserRole(Integer userId, String role) {
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        int result = userMapper.updateUserRole(userId, role);
        if (result <= 0) {
            throw new RuntimeException("更新用户角色失败");
        }
    }
    
    /**
     * 更新用户状态（管理员功能）
     */
    public void updateUserStatus(Integer userId, String status) {
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        int result = userMapper.updateUserStatus(userId, status);
        if (result <= 0) {
            throw new RuntimeException("更新用户状态失败");
        }
    }
    
    /**
     * 删除用户（管理员功能）
     */
    public void deleteUser(Integer userId) {
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        int result = userMapper.deleteById(userId);
        if (result <= 0) {
            throw new RuntimeException("删除用户失败");
        }
    }
    
    /**
     * 验证用户权限
     */
    public boolean hasPermission(Integer userId, String requiredRole) {
        User user = userMapper.findById(userId);
        if (user == null) {
            return false;
        }
        
        String userRole = user.getUserRole();
        
        // 管理员拥有所有权限
        if ("ADMIN".equals(userRole)) {
            return true;
        }
        
        // 检查是否匹配要求的角色
        return requiredRole.equals(userRole);
    }
    
    /**
     * 检查是否已存在管理员账户
     */
    public boolean hasAdmin() {
        return userMapper.countUsersByRole("ADMIN") > 0;
    }
    
    /**
     * 获取用户总数
     */
    public long getTotalUserCount() {
        return userMapper.countUsers();
    }
    
    /**
     * 获取今天新注册的用户数
     */
    public long getTodayNewUserCount() {
        // 这里应该查询今天注册的用户数，暂时返回模拟数据
        return 12;
    }
    
    /**
     * 获取活跃用户数（比如最近30天有登录的用户）
     */
    public long getActiveUserCount() {
        // 这里应该查询活跃用户数，暂时返回模拟数据
        return userMapper.countUsers() - 50; // 假设有50个不活跃用户
    }
    
    /**
     * 获取管理员用户数
     */
    public long getAdminUserCount() {
        return userMapper.countUsersByRole("ADMIN");
    }
    
    /**
     * 创建管理员账户
     */
    public UserInfoResponse createAdmin(String username, String email, String password) {
        // 检查是否已存在管理员
        if (hasAdmin()) {
            throw new RuntimeException("管理员账户已存在");
        }
        
        // 检查用户名是否已存在
        if (userMapper.findByUsername(username) != null) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 检查邮箱是否已存在
        if (userMapper.findByEmail(email) != null) {
            throw new RuntimeException("邮箱已被注册");
        }
        
        // 创建新管理员用户
        User user = new User();
        user.setUsername(username);
        user.setPassword(passwordEncoder.encode(password));
        user.setEmail(email);
        user.setRegisterDate(LocalDateTime.now());
        user.setUserRole("ADMIN");
        user.setStatus("ACTIVE");
        
        // 保存用户
        int result = userMapper.insert(user);
        if (result <= 0) {
            throw new RuntimeException("创建管理员账户失败");
        }
        
        // 生成JWT token
        String token = jwtUtil.generateToken(user.getUserId(), user.getUsername(), user.getUserRole());
        
        // 返回用户信息
        return convertToUserInfoResponse(user, token);
    }
    
    /**
     * 将User实体转换为UserInfoResponse
     */
    private UserInfoResponse convertToUserInfoResponse(User user, String token) {
        UserInfoResponse response = new UserInfoResponse();
        
        // 基本字段映射
        response.setUserId(user.getUserId());
        response.setUsername(user.getUsername());
        response.setEmail(user.getEmail());
        response.setPhone(user.getPhone());
        response.setRegisterDate(user.getRegisterDate());
        response.setLastLogin(user.getLastLogin());
        response.setUserRole(user.getUserRole());
        response.setProfilePicture(user.getProfilePicture());
        response.setStatus(user.getStatus() != null ? user.getStatus() : "ACTIVE");
        response.setToken(token);
        
        return response;
    }
    
    /**
     * 批量删除用户
     */
    public void batchDeleteUsers(List<Integer> userIds) {
        for (Integer userId : userIds) {
            deleteUser(userId);
        }
    }
    
    /**
     * 批量设置用户角色
     */
    public void batchSetRole(List<Integer> userIds, String role) {
        for (Integer userId : userIds) {
            updateUserRole(userId, role);
        }
    }
    
    /**
     * 批量设置用户状态
     */
    public void batchSetStatus(List<Integer> userIds, String status) {
        for (Integer userId : userIds) {
            updateUserStatus(userId, status);
        }
    }
} 